﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chefbook.DataObjects;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace Chefbook.ViewModels
{
    /// <summary>
    /// View Model for treeview displaying all categories
    /// </summary>
    public class CategoryTreeViewModel : ViewModelBase
    {
        ObservableCollection<CategoryViewModel> rootCategories;
        CategoryViewModel selectedCategory;

        /// <summary>
        /// Creates a new viewmodel for treeview displaying all categories
        /// </summary>
        /// <param name="rootCategories">A list of all root categories</param>
        public CategoryTreeViewModel(IEnumerable<CategoryViewModel> rootCategories)
        {
            this.rootCategories = new ObservableCollection<CategoryViewModel>(rootCategories);
            selectedCategory = rootCategories.FirstOrDefault();
            selectedCategory.IsSelected = true;
            foreach (var category in rootCategories)
            {
                ListenPropertyChangedOnAllSubs(category);
            }
        }

        private void ListenPropertyChangedOnAllSubs(CategoryViewModel category)
        {
            category.PropertyChanged += categoryPropertyChanged;
            foreach (var subcategory in category.Subcategories)
            {
                ListenPropertyChangedOnAllSubs(subcategory);
            }
        }

        void categoryPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsSelected")
            {
                var category = (CategoryViewModel)sender;
                if (category.IsSelected)
                { SelectedCategory = category; }
            }
        }

        /// <summary>
        /// Gets the root categories of the tree
        /// </summary>
        public ReadOnlyObservableCollection<CategoryViewModel> RootCategories
        {
            get { return new ReadOnlyObservableCollection<CategoryViewModel>(rootCategories); }
        }

        /// <summary>
        /// Gets or sets the currently selected category
        /// </summary>
        public CategoryViewModel SelectedCategory
        {
            get { return selectedCategory; }
            set
            {
                if (selectedCategory != value)
                {
                    var oldSelection = selectedCategory;
                    selectedCategory = value;

                    oldSelection.IsSelected = false;
                    selectedCategory.IsSelected = true; //New selection
                    OnPropertyChanged("SelectedCategory");
                }
            }
        }


    }
}
